//
//  YPWebController.swift
//  FZ_Thermometer
//
//  Created by Li Dong on 2023/3/17.
//

import UIKit
import WebKit
import SnapKit
import HandyJSON
import Alamofire

class YPFileModel: HandyJSON {
    required init() {
    }
    
    var fileId = ""
    var fileName = ""
    var postfix = ""
    var type = ""
    var urlPage = ""
    
    var file = ""
    
    var url = ""
    var name = ""
    var thumb = ""
}

class JSCallBackModel: HandyJSON {
    required init() {
        
    }
    var callback = ""
}

class SiWebVC: SiBaseVC {
    
    var webView: WKWebView!
    var url = ""
    var navView = UIView()
    
    var jsMethodName = ""
    var needCallJs = false
    var downloadTask: DownloadRequest?
    
    init(url: String = "") {
        super.init(nibName: nil, bundle: nil)
        self.url = url
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        hideNavgaitionBar()
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        config.userContentController = WKUserContentController()
        config.userContentController.add(self, name: "setLocation")
        config.userContentController.add(self, name: "shareFn")
        config.userContentController.add(self, name: "closeWebview")
        config.userContentController.add(self, name: "saveFile")
        config.userContentController.add(self, name: "hasPurchased")
        config.userContentController.add(self, name: "webClose")
        config.userContentController.add(self, name: "saveImg")
        config.userContentController.add(self, name: "shareFile")
        config.userContentController.add(self, name: "saveLivePhote")
        webView = WKWebView(frame: .zero, configuration: config)
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }


        
        if let temp = URL(string: url) {
            let request = URLRequest(url: temp)
            webView.load(request)
        }
        
    }
    
    
    deinit {
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "setLocation")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "shareFn")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "closeWebview")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveFile")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "hasPurchased")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "webClose")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveImg")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "shareFile")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveLivePhote")
        downloadTask?.cancel()
    }

    
    func jumpIPhoneSetting() {
        UIApplication.shared.open(URL.init(string: UIApplication.openSettingsURLString)!, options: [:],
                                  completionHandler: {
                                    (success) in
        })
    }
    
    func shareHandler(model: YPFileModel) {
        self.showHUD(withDetail: NSLocalizedString("正在下载", comment: ""))
        guard let tempUrl = URL(jlStr: model.url) else {
            return
        }
        let fileName = (model.fileName.decoderUrlEncodeStr() ?? "") + "." + tempUrl.pathExtension
        downloadTask = APICenter.downloadFile(fileUrl: model.url, name: fileName, downloadProgress: nil) {[weak self] fileUrl   in
            self?.dismissHUD()
            guard let fileUr = fileUrl else {
                return
            }
            let activityItems = [fileUr]
            let activityVC = UIActivityViewController(activityItems: activityItems as [Any], applicationActivities: nil)
            activityVC.excludedActivityTypes = [UIActivity.ActivityType.print,
                                                UIActivity.ActivityType.copyToPasteboard,
                                                UIActivity.ActivityType.assignToContact,
                                                UIActivity.ActivityType.saveToCameraRoll]
            self?.present(activityVC, animated: true, completion: nil)
        }
    }
    
    override func popHandler() {
        if webView.canGoBack {
            webView.goBack()
        }else{
            super.popHandler()
        }
    }
    
    func saveFile(model: YPFileModel)  {
//        var list = model.file.split(separator: ",")
//        var base64String = model.file
//        if !list.isEmpty {
//            base64String = base64String.replacingOccurrences(of: list[0] + ",", with: "")
//        }
//
//        guard let fileData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters) else {
//            print("保存文件失败")
//            return
//        }
//        CompressedHelper.shared.writeData(data: fileData, fileName: model.name)
//
//        let activityItems = [URL(fileURLWithPath: CompressedHelper.shared.getFilePath(fileName: model.name))]
//        let activityVC = UIActivityViewController(activityItems: activityItems as [Any], applicationActivities: nil)
//        activityVC.excludedActivityTypes = [UIActivity.ActivityType.print,
//                                            UIActivity.ActivityType.copyToPasteboard,
//                                            UIActivity.ActivityType.assignToContact,
//                                            UIActivity.ActivityType.saveToCameraRoll]
//        present(activityVC, animated: true, completion: nil)
    }
    

    func sendJsMethod(jsMethodName: String)  {
        if jsMethodName.isEmpty {
            return
        }
        webView.evaluateJavaScript(jsMethodName) { _, error in
            if let err = error {
                print("evaluateJavaScript err = ", err.localizedDescription)
            }
        }
    }

    func saveImgToAlbum(picUrl: String)  {
        self.showAnnularProgressHUD(withDetail: NSLocalizedString("正在下载", comment: ""))
        let tempUrl = URL(jlStr: picUrl)
       downloadTask = APICenter.downloadFile(fileUrl: picUrl, name: "temp_img." + (tempUrl?.pathExtension ?? "jpg")) { progress in
            self.progressHUD?.progress = progress
            self.progressHUD?.detailsLabel.text = String(format: "%@%.0f%%", NSLocalizedString("正在下载", comment: ""), progress*100)
        } finish: {[weak self] fileUrl in
            self?.dismissHUD()
            guard let fileUr = fileUrl else {
                self?.showHUDTextOnly(NSLocalizedString("保存失败", comment: ""))
                self?.sendJsMethod(jsMethodName: "saveImgCallback(0)")
                return
            }
            guard let img = UIImage(contentsOfFile: fileUr.path) else {
                self?.showHUDTextOnly(NSLocalizedString("保存失败", comment: ""))
                self?.sendJsMethod(jsMethodName: "saveImgCallback(0)")
                return
            }
            self?.doSaveImg(img: img)//savelmgCallback
        }

    }

    func doSaveImg(img: UIImage)  {
        UIImageWriteToSavedPhotosAlbum(img, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)

    }

    @objc func image(image: UIImage,didFinishSavingWithError: NSError?,contextInfo: AnyObject)  {
        if didFinishSavingWithError == nil {
            sendJsMethod(jsMethodName: "saveImgCallback(1)")
        }else{
            showHUDTextOnly(NSLocalizedString("保存失败", comment: ""))
            sendJsMethod(jsMethodName: "saveImgCallback(0)")
        }
    }
    
    func saveVideo(videoUrl: String, thumbUrl: String)  {
        self.showAnnularProgressHUD(withDetail: NSLocalizedString("正在下载", comment: ""))
        var tempVideoUrl: URL!
        let tempUrl = URL(jlStr: videoUrl)
        let fileName = tempUrl?.lastPathComponent ?? "temp.mp4"
        downloadTask = APICenter.downloadFile(fileUrl: videoUrl, name: fileName) { progress in
            self.progressHUD?.progress = progress
            self.progressHUD?.detailsLabel.text = String(format: "%@%.0f%%", NSLocalizedString("正在下载", comment: ""), progress*100)
        } finish: {[weak self] fileUrl in
            guard let self = self else {
                return
            }
            self.dismissHUD()
            guard let fileUr = fileUrl else {
//                self.showHUDTextOnly("保存失败")
                self.sendJsMethod(jsMethodName: "saveLivePhoteCallback(0)")
                return
            }
            tempVideoUrl = fileUr
            self.saveLivePhoto(videoUrl: tempVideoUrl)
        }
    }
    
    func saveLivePhoto(videoUrl: URL)  {
        let targetPath = CompressedHelper.shared.getFilePath(fileName: "temp_video_new.MOV")
        if FileManager.default.fileExists(atPath: targetPath) {
            try? FileManager.default.removeItem(atPath: targetPath)
        }
        let assetIdentifier = UUID().uuidString
        let videoPath = URL(fileURLWithPath: targetPath)
        
        let movUtils = QuickTimeMov(path: videoUrl.path)
        movUtils.write(targetPath, assetIdentifier: assetIdentifier) {[weak self] suc in
            guard let self = self else {
                return
            }
            if !suc {
                DispatchQueue.main.async {
                    self.showHUDTextOnly(NSLocalizedString("保存失败", comment: ""))
                }
            }
            LiveUtils.createLivePhotoFromVideo(videoURL: videoPath, assetIdentifier: assetIdentifier) {[weak self] suc in
                guard let self = self else {
                    return
                }
                DispatchQueue.main.async {
                    if suc {
                        self.sendJsMethod(jsMethodName: "saveLivePhoteCallback(1)")
                    }else{
//                        self.showHUDTextOnly("保存失败")
                        self.sendJsMethod(jsMethodName: "saveLivePhoteCallback(0)")
                    }
                }

            }
        }
    }

    
}




extension SiWebVC: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("message.name = ", message.name)
        if message.name == "setLocation" {
            jumpIPhoneSetting()
        }else if message.name == "shareFn" {
            print("message.body = ", message.body)
            guard let temp = message.body as? [String: Any]  else {
                return
            }
            if let mm = YPFileModel.deserialize(from: temp) {
                shareHandler(model: mm)
            }
        }else if message.name == "closeWebview" || message.name == "webClose"{
            popHandler()
        }else if message.name == "saveFile" {
            guard let temp = message.body as? [String: Any]  else {
                return
            }
            if let mm = YPFileModel.deserialize(from: temp) {
                saveFile(model: mm)
            }
        }else if message.name == "hasPurchased" {
//            guard let temp = message.body as? [String: Any]  else {
//                return
//            }
//            if let mm = JSCallBackModel.deserialize(from: temp) {
                //                if !AppProducts.shared.isPurchased {
                //                    showSubVC()
                //                    sendPurcaseResult(jsMethodName: mm.callback)
                //                    return
                //                }
//                sendPurcaseResult(jsMethodName: mm.callback)
//            }
            
        }else if message.name == "saveImg" {
            guard let temp = message.body as? [String: Any]  else {
                return
            }
            PermissionUtils.albumAndCamera(type: .photoLibrary) {[weak self] in
                if let mm = YPFileModel.deserialize(from: temp) {
                    self?.saveImgToAlbum(picUrl: mm.url)
                }
            } fail: {[weak self] in
                self?.sendJsMethod(jsMethodName: "saveImgCallback(0)")
            }

        }else if message.name == "shareFile" {
            guard let temp = message.body as? [String: Any]  else {
                return
            }
            if let mm = YPFileModel.deserialize(from: temp) {
                saveFile(model: mm)
            }
        }else if message.name == "saveLivePhote" {
            guard let temp = message.body as? [String: Any]  else {
                return
            }
            PermissionUtils.albumAndCamera(type: .photoLibrary) {[weak self] in
                if let mm = YPFileModel.deserialize(from: temp) {
                    self?.saveVideo(videoUrl: mm.url, thumbUrl: mm.thumb)
                }
            } fail: {[weak self] in
                self?.sendJsMethod(jsMethodName: "saveLivePhoteCallback(0)")
            }
        }
    }
}


